import express from "express";
import { StatisticsService } from "../../services/school/statisticsService.mjs";
import { School } from "../../models/School.mjs";
import { Province } from "../../models/Province.mjs";
import { Statistics } from "../../models/Statistics.mjs";
import { CollegeInfo } from "../../models/College-info.js";
import {
  calculateProvinceScores,
  analyzeProvinceTrend,
  analyzeNationalTrend,
  analyzeAllProvincesTrend,
} from "../../utils/index.mjs";

const router = express.Router();

/**
 * @swagger
 * /api/statistics/update:
 *   post:
 *     summary: 更新统计数据
 *     description: 更新统计数据
 *     responses:
 *       200:
 *         description: 统计数据更新成功
 */
// 更新统计数据
router.post("/update", async (req, res) => {
  try {
    const schools = await School.find();
    const provinces = await Province.find();
    const statistics = await StatisticsService.updateStatistics(
      schools,
      provinces
    );
    res.json(statistics);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

/**
 * @swagger
 * /api/statistics:
 *   get:
 *     summary: 获取统计数据
 *     description: 获取统计数据
 *     responses:
 *       200:
 *         description: 统计数据获取成功
 */
// 获取统计数据
router.get("/", async (req, res) => {
  try {
    const statistics = await Statistics.findOne({ type: "school" });
    if (!statistics) {
      return res.status(404).json({ message: "未找到统计数据" });
    }
    res.json(statistics);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

/**
 * @swagger
 * /api/statistics/major-word-cloud:
 *   get:
 *     summary: 获取专业词云数据
 *     description: 获取专业词云数据
 *     responses:
 *       200:
 *         description: 专业词云数据获取成功
 */
// 获取专业词云数据
router.get("/major-word-cloud", async (req, res) => {
  try {
    const schools = await School.find();
    const majorCount = new Map();

    schools.forEach((school) => {
      school.children?.forEach((major) => {
        const name = major.special_name;
        majorCount.set(name, (majorCount.get(name) || 0) + 1);
      });
    });

    // 转换为数组并排序
    const wordCloudData = Array.from(majorCount.entries())
      .map(([name, count]) => ({
        name,
        value: count,
      }))
      // 按数量降序排序
      .sort((a, b) => b.value - a.value)
      // 只取前100条
      .slice(0, 100);

    res.json({
      data: wordCloudData,
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

/**
 * @swagger
 * /api/statistics/major-distribution:
 *   get:
 *     summary: 获取专业分布数据（按学科门类统计）
 *     description: 获取专业分布数据（按学科门类统计）
 *     responses:
 *       200:
 *         description: 专业分布数据获取成功
 */
// 获取专业分布数据（按学科门类统计）
router.get("/major-distribution", async (req, res) => {
  try {
    // 从统计数据中获取专业分布
    const statistics = await Statistics.findOne({ type: "school" });

    if (statistics && statistics.data.majorDistribution) {
      return res.json({
        data: statistics.data.majorDistribution,
        lastUpdated: statistics.lastUpdated,
      });
    }

    const schools = await School.find();
    const provinces = await Province.find();
    const stats = await updateStatistics(schools, provinces);

    res.json({
      data: stats.majorDistribution,
      lastUpdated: new Date(),
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

/**
 * @swagger
 * /api/statistics/employment-trend:
 *   get:
 *     summary: 获取就业率趋势数据
 *     description: 获取就业率趋势数据
 *     responses:
 *       200:
 *         description: 就业率趋势数据获取成功
 */
// 获取就业率趋势数据
router.get("/employment-trend", async (req, res) => {
  try {
    const provinces = await Province.find(
      {},
      {
        name: 1,
        statistics: {
          $elemMatch: { name: "employment" },
        },
      }
    );

    const nationalTrend =
      provinces[0]?.statistics[0]?.yearlyData.map((year) => ({
        year: year.year.toString(),
        value: (
          provinces.reduce((sum, province) => {
            const yearData = province.statistics[0]?.yearlyData.find(
              (y) => y.year === year.year
            );
            return sum + (yearData?.value || 0);
          }, 0) / provinces.length
        ).toFixed(2),
      })) || [];

    const provinceTrends = provinces.map((province) => ({
      name: province.name,
      data:
        province.statistics[0]?.yearlyData.map((yearData) => ({
          year: yearData.year.toString(),
          value: yearData.value.toFixed(2),
        })) || [],
    }));

    res.json({
      nationalTrend,
      provinceTrends,
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

/**
 * @swagger
 * /api/statistics/salary-comparison:
 *   get:
 *     summary: 获取收入水平数据
 *     description: 获取收入水平数据
 *     responses:
 *       200:
 *         description: 收入水平数据获取成功
 */
// 获取收入水平数据
router.get("/salary-comparison", async (req, res) => {
  try {
    const provinces = await Province.find(
      {},
      {
        name: 1,
        type: 1,
        statistics: {
          $elemMatch: { name: "income" },
        },
      }
    );

    // 计算全国平均趋势
    const nationalTrend =
      provinces[0]?.statistics[0]?.yearlyData.map((year) => ({
        year: year.year.toString(),
        value: (
          provinces.reduce((sum, province) => {
            const yearData = province.statistics[0]?.yearlyData.find(
              (y) => y.year === year.year
            );
            return sum + (yearData?.value || 0);
          }, 0) / provinces.length
        ).toFixed(2),
      })) || [];

    // 各省份趋势
    const provinceTrends = provinces.map((province) => ({
      name: province.name,
      data:
        province.statistics[0]?.yearlyData.map((year) => ({
          year: year.year.toString(),
          value: year.value.toFixed(2),
        })) || [],
    }));

    res.json({
      nationalTrend, // 全国平均趋势
      provinceTrends, // 各省份趋势
      unit: "元/年", // 单位
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

/**
 * @swagger
 * /api/statistics/province-scores:
 *   get:
 *     summary: 获取省份综合评分数据
 *     description: 获取全国和各省份的综合评分雷达图数据
 *     responses:
 *       200:
 *         description: 省份综合评分数据获取成功
 */
router.get("/province-scores", async (req, res) => {
  try {
    // 从统计数据中获取省份评分
    const statistics = await Statistics.findOne({ type: "school" });

    if (statistics && statistics.data.provinceScores.length > 0) {
      return res.json({
        data: statistics.data.provinceScores,
        lastUpdated: statistics.lastUpdated,
      });
    }

    const provinces = await Province.find();

    const scores = await calculateProvinceScores(provinces);

    // 验证数据
    const isValid = scores.provinces.every((province) =>
      Object.values(province.scores).every(
        (score) => !isNaN(score) && isFinite(score)
      )
    );

    if (!isValid) {
      throw new Error("计算结果包含无效数据");
    }

    // 更新统计数据
    if (statistics) {
      statistics.data.provinceScores = scores;
      statistics.lastUpdated = new Date();
      await statistics.save();
    }

    res.json({
      data: scores,
      lastUpdated: new Date(),
    });
  } catch (error) {
    console.error("获取省份评分错误:", error);
    res.status(500).json({ message: error.message });
  }
});

// 获取发展趋势数据
router.get("/trend", async (req, res) => {
  try {
    const [nationalTrend, provincesTrend] = await Promise.all([
      analyzeNationalTrend(),
      analyzeAllProvincesTrend(),
    ]);

    res.json({
      success: true,
      data: {
        national: nationalTrend,
        provinces: provincesTrend,
      },
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message,
    });
  }
});

// 获取单个省份的发展趋势
router.get("/trend/:provinceName", async (req, res) => {
  try {
    const { provinceName } = req.params;
    const trend = await analyzeProvinceTrend(provinceName);
    res.json({
      success: true,
      data: trend,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message,
    });
  }
});

/**
 * @swagger
 * /api/statistics/college-rankings:
 *   get:
 *     summary: 获取大学排名数据
 *     description: 获取大学排名数据，支持分页和条件查询
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *         description: 页码，默认为1
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *         description: 每页数量，默认为10
 *       - in: query
 *         name: query
 *         schema:
 *           type: string
 *         description: 查询条件，可以是学校名称、地区或类型
 *     responses:
 *       200:
 *         description: 大学排名数据获取成功
 */
// 获取大学排名数据
router.get("/college-rankings", async (req, res) => {
  try {
    const { page = 1, limit = 10, query } = req.query;
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    const skip = (pageNum - 1) * limitNum;

    // 构建查询条件
    let filter = {};
    if (query) {
      filter = {
        $or: [
          { name: { $regex: query, $options: "i" } },
          { location: { $regex: query, $options: "i" } },
          { type: { $regex: query, $options: "i" } },
        ],
      };
    }

    // 查询数据
    const [colleges, total] = await Promise.all([
      CollegeInfo.find(filter)
        .sort({ rank: 1 }) // 按排名升序排列
        .skip(skip)
        .limit(limitNum)
        .select("name rank location type score historical_scores"),
      CollegeInfo.countDocuments(filter),
    ]);

    res.json({
      success: true,
      data: {
        colleges,
        pagination: {
          total,
          page: pageNum,
          limit: limitNum,
          pages: Math.ceil(total / limitNum),
        },
      },
    });
  } catch (error) {
    console.error("获取大学排名数据错误:", error);
    res.status(500).json({
      success: false,
      message: error.message,
    });
  }
});

/**
 * @swagger
 * /api/statistics/college-geo:
 *   get:
 *     summary: 获取大学地理信息
 *     description: 获取大学地理信息，返回经纬度不为空的数据
 *     responses:
 *       200:
 *         description: 大学地理信息获取成功
 */
// 获取大学地理信息
router.get("/college-geo", async (req, res) => {
  try {
    // 查询经纬度不为空的数据
    const colleges = await CollegeInfo.find({
      "coordinates.lng": { $exists: true, $ne: null },
      "coordinates.lat": { $exists: true, $ne: null },
    }).select("name location coordinates");

    res.json({
      success: true,
      data: colleges,
    });
  } catch (error) {
    console.error("获取大学地理信息错误:", error);
    res.status(500).json({
      success: false,
      message: error.message,
    });
  }
});

/**
 * @swagger
 * /api/statistics/major-categories:
 *   get:
 *     summary: 获取指定学科门类下的子分类
 *     description: 根据学科门类名称获取其下的子分类信息
 *     parameters:
 *       - in: query
 *         name: category
 *         schema:
 *           type: string
 *         required: true
 *         description: 学科门类名称
 *     responses:
 *       200:
 *         description: 成功获取子分类数据
 *       404:
 *         description: 未找到指定的学科门类
 */
router.get("/major-categories", async (req, res) => {
  try {
    const { category } = req.query;
    if (!category) {
      return res.status(400).json({ message: "请提供学科门类名称" });
    }
    const statistics = await Statistics.findOne({ type: "school" });
    if (!statistics || !statistics.data.majorHierarchy) {
      return res.status(404).json({ message: "未找到统计数据" });
    }
    const { majorHierarchy } = statistics.data;
    // 查找指定的一级学科
    const level1Major = majorHierarchy.level1.find(
      (l1) => l1.name === category
    );
    if (!level1Major) {
      return res.status(404).json({ message: "未找到指定的学科门类" });
    }
    // 获取该一级学科下的二级学科
    const level2Codes =
      majorHierarchy.relationships.level1ToLevel2.get(level1Major.code) || [];
    const level2Majors = level2Codes
      .map((code) => majorHierarchy.level2.find((l2) => l2.code === code))
      .filter(Boolean);
    // 获取每个二级学科下的三级专业
    const result = level2Majors.map((level2) => {
      const level3Codes =
        majorHierarchy.relationships.level2ToLevel3.get(level2.code) || [];
      const level3Majors = level3Codes
        .map((code) => majorHierarchy.level3.find((l3) => l3.code === code))
        .filter(Boolean);
      return {
        name: level2.name,
        code: level2.code,
        value: level2.value,
        children: level3Majors.map((major) => ({
          name: major.name,
          code: major.code,
          value: major.value,
          type: major.type,
        })),
      };
    });
    res.json({
      success: true,
      data: {
        category: level1Major.name,
        code: level1Major.code,
        value: level1Major.value,
        subCategories: result,
      },
    });
  } catch (error) {
    console.error("获取学科门类子分类错误:", error);
    res.status(500).json({ message: error.message });
  }
});

export default router;
